<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Debug;
use app\models\{Order, Wechat, Payment, Coupon, Agent, OrderProduct, Product, Douyin, User as Users};
use think\Db;
use think\facade\Log;
use app\facade\Redis;

class Refund extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('Refund')->setDescription('订单退款、完成等');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        ini_set('max_execution_time', 0);
        //未支付订单取消
        $time = date('Y-m-d H:i:s', time() - 10 * 60);
        (new Order())->where(['status' => 1])->where('created', '<=', $time)->chunk(5, function ($lists) {
            foreach ($lists as $list) {
                $frtimes = Redis::get('ordercacel' . $list['id']);
                if ($frtimes) {
                    break;
                } else {
                    Redis::setex('ordercacel' . $list['id'], 5, 5);
                }
                $coupon = json_decode($list['coupons'], true) ?? [];
                Db::startTrans();
                try {
                    if ($list['coupon'] > 0) {
                        (new Coupon())->where('id', $list['coupon'])->update(['status' => 1]);
                    }
                    if (count($coupon) > 0) {
                        (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
                    }
                    (new Order())->where('id', $list['id'])->update([
                        'status' => 5,
                        'caceltime' => date('Y-m-d H:i:s')
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                    break;
                }
            }
        });
        //已支付订单3天未接单超时取消
        $times = date('Y-m-d H:i:s', time() - 86400 * 3);
        (new Order())->where(['status' => 2])->where('created', '<=', $times)->chunk(5, function ($lists) {
            foreach ($lists as $list) {
                $frtimes = Redis::get('ordercacel' . $list['id']);
                if ($frtimes) {
                    break;
                } else {
                    Redis::setex('ordercacel' . $list['id'], 5, 5);
                }
                $coupon = json_decode($list['coupons'], true) ?? [];
                Db::startTrans();
                try {
                    if ($list['coupon'] > 0) {
                        (new Coupon())->where('id', $list['coupon'])->update(['status' => 1]);
                    }
                    if (count($coupon) > 0) {
                        (new Coupon())->where(['id' => $coupon])->update(['status' => 1]);
                    }
                    (new Order())->where('id', $list['id'])->update([
                        'status' => 5,
                        'caceltime' => date('Y-m-d H:i:s'),
                        'refund' => 2,
                        'info' => $list['info'] . '未接单取消'
                    ]);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                    break;
                }
            }
        });
        //完成订单结款
        (new Order())->where(['status' => 4, 'income' => 1])->chunk(5, function ($lists) {
            foreach ($lists as $list) {
                $frtimes = Redis::get('orderFinsh' . $list['id']);
                if ($frtimes) {
                    break;
                } else {
                    Redis::setex('orderFinsh' . $list['id'], 5, 5);
                }
                //查找下面的商品库增加销量
                $orderproduct = (new OrderProduct())->where('ordersn', $list['ordersn'])->select();
                $coupon = json_decode($list['coupons'], true) ?? [];
                Db::startTrans();
                try {
                    (new Order())->where(['status' => $list['status'], 'id' => $list['id']])->update(['income' => 2]);
                    foreach ($orderproduct as $product) {
                        (new Product())->where('id', $product['productid'])->setInc('sales', $product['number']);
                    }
                    if ($list['payment'] > 1) {
                        (new Agent())->MoneyEdit($list['agentid'], 1, $list['total'], '下单支付结算', $list['id']);
                    }
                    if ($list['coupon'] > 0) {
                        (new Coupon())->where(['id' => $list['coupon']])->update(['endstatus' => 2]);
                    }
                    if (count($coupon) > 0) {
                        $btArr = [];
                        foreach ($coupon as $coupons) {
                            $coupon = (new Coupon())->where(['id' => $coupons, 'types' => 2])->find();
                            if (!empty($coupon) && $coupon['btmoney'] > 0) {
                                if (empty($btArr[$coupon['agentid']])) {
                                    $btArr[$coupon['agentid']] = 0;
                                }
                                $btArr[$coupon['agentid']] += $coupon['btmoney'];
                            }
                            (new Coupon())->where(['id' => $coupons, 'types' => 2])->update(['endstatus' => 2]);
                        }
                        foreach ($btArr as $k => $v) {
                            if ($k == $list['agentid']) {
                                (new Agent())->MoneyEdit2($list['agentid'], 1, -$v, '自家优惠券使用抵扣', $list['id']);
                            } else {
                                (new Agent())->MoneyEdit($list['agentid'], 1, $v, '优惠卡补贴', $list['id']);
                            }
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    dump($e->getMessage());
                    Db::rollback();
                    break;
                }
            }
        });
        //取消订单退款
        (new Order())->where(['status' => 5, 'refund' => 2])->chunk(1, function ($lists) {
            foreach ($lists as $list) {
                $frtimes = Redis::get('orderRefund' . $list['id']);
                if ($frtimes) {
                    break;
                } else {
                    Redis::setex('orderRefund' . $list['id'], 5, 5);
                }
                if ($list['payment'] == 4) {
                    $user = (new Users())->where('id', $list['user_id'])->find();
                    Db::startTrans();
                    try {
                        (new Order())->where(['status' => $list['status'], 'id' => $list['id']])->update(['refund' => 3, 'caceltime' => date('Y-m-d H:i:s')]);
                        if ($list['coupon'] > 0) {
                            (new Coupon())->where('id', $list['coupon'])->update(['status' => 1]);
                        }
                        (new Users())->MondyEdit($user['id'], $user['money'], $list['total'], 3, 0, '支付订单取消');
                        Db::commit();
                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        Db::rollback();
                        break;
                    }
                } else {
                    $payment = (new Payment())->where(['ordersn' => $list['ordersn'], 'status' => 2, 'type' => 1])->find();
                    if (empty($payment) || $list['payment'] == 0 || $list['payment'] == 1 || $payment['refund'] == 2) {
                        Db::startTrans();
                        try {
                            (new Order())->where(['status' => $list['status'], 'id' => $list['id']])->update(['refund' => 3, 'caceltime' => date('Y-m-d H:i:s')]);
                            if ($list['coupon'] > 0) {
                                (new Coupon())->where('id', $list['coupon'])->update(['status' => 1]);
                            }
                            Db::commit();
                        } catch (\Exception $e) {
                            dump($e->getMessage());
                            Db::rollback();
                            break;
                        }
                    } else {
                        switch ($payment['paytype']) {
                                //微信支付退款
                            case '1':
                                $refundInfo['refund_id'] = $payment['paymentid'];
                                $refundInfo['money'] = $payment['money'];
                                $paymentInfo['params'] = $payment['paydata'];
                                $paymentInfo['payment_id'] =  $payment['paymentid'];
                                $paymentInfo['money'] = $payment['money'];
                                $res = (new Wechat())->refund($refundInfo, $paymentInfo);
                                dump($res);
                                break;
                            case '2':
                                $refundInfo['refund_id'] = $payment['paymentid'];
                                $refundInfo['money'] = $payment['money'];
                                $paymentInfo['params'] = $payment['paydata'];
                                $paymentInfo['payment_id'] =  $payment['paymentid'];
                                $paymentInfo['money'] = $payment['money'];
                                $res = (new Douyin())->refund($refundInfo, $paymentInfo);
                                dump($res);
                                break;
                            default:
                                # code...
                                break;
                        }
                    }
                }
            }
        });

        //抖音抄8未结算订单自动结算
        $time2 = date('Y-m-d H:i:s', time() - 7 * 86400);
        (new Payment())->where(['paytype' => 2, 'status' => 2, 'refund' => 1, 'fz' => [1, -1]])->where('created', '<=', $time2)->chunk(1, function ($lists) {
            foreach ($lists as $list) {
                $name = 'paymentsettle' . $list['id'];
                $frtimes = Redis::get($name);
                if ($frtimes) {
                    break;
                } else {
                    //核销
                    if ($list['fz'] == 1) {
                        if (empty($list['user_id'])) {
                            $list['user_id'] = 1;
                        }
                        $user = (new Users())->where('id', $list['user_id'])->find();
                        if ($user['type'] == 1) {
                            $openid = $user['dyopenid'];
                        } else {
                            $openid = $user['openid'];
                        }
                        $detail = [
                            'order_id' => $list['paymentid'],
                            'create_time' => strtotime($list['created']) * 1000,
                            'status' => '已支付',
                            'total_price' => $list['money'] * 100,
                            'detail_url' => '/',
                            'item_list' => [[
                                'img' => '',
                                'title' => '小程序消费',
                                'price' => $list['money'] * 100
                            ]]
                        ];
                        $payment['openid'] = $openid;
                        $payment['detail'] = $detail;
                        $res = (new Douyin())->push($payment);
                        dump($res);
                        if (isset($res['err_code']) && $res['err_code'] == 0) {
                            Redis::setex($name, 3 * 86400, 3 * 86400);
                            (new Payment())->where('id', $list['id'])->update(['fz' => -1]);
                        }
                    } else {
                        $payment['paymentid'] = $list['paymentid'];
                        $payment['out_order_no'] = $list['paymentid'];
                        $payment['text'] = '主动结算';
                        $res = (new Douyin())->settle($payment);
                        if (isset($res['err_no'])) {
                            //查询分账情况
                            if ($res['err_no'] == 0 || $res['err_no'] == 2000 || $res['err_no'] == 2014 || $res['err_no'] == 2000 || $res['err_no'] == 3110 || $res['err_no'] == 3106) {
                                (new Payment())->where('id', $list['id'])->update(['fz' => $res['err_no']]);
                            } else {
                                Redis::setex($name, 86400, 86400);
                            }
                            dump($res);
                        }
                    }
                }
            }
        });

        //接单周期抄15天订单自动完成
        $timeend = date('Y-m-d H:i:s', time() - 15 * 86400);
        (new Order())->where(['status' => 3])->whereTime('ordertime', '<', $timeend)->chunk(10, function ($lists) {
            foreach ($lists as $order) {
                $frtimes = Redis::get('orderends' . $order['id']);
                if ($frtimes) {
                    continue;
                } else {
                    Redis::setex('orderends' . $order['id'], 86400, 86400);
                }
                //完成订单
                $user =  (new Users())->where('id', $order['user_id'])->find();
                Db::startTrans();
                try {
                    (new Order())->where('id', $order['id'])->update([
                        'status' => 4,
                        'endtime' => date('Y-m-d H:i:s'),
                        'info' => $order['info'] . '未确认自动确认'
                    ]);
                    (new Users())->IntergralEdit($user['id'], $user['integral'], $order['total'], 1, $order['id'], '下单赠送');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->result([], 1, $e->getMessage());
                }
            }
        });
    }
}
